package ii.oo.liu;

import java.io.*;
import java.util.*;

/**
 * Created by Admin on 1/6 0006.
 */
public class FileDemo {
    public static void main(String[] args) throws Exception {
//       splitFile();
        merge();
    }

    public static void splitFile() {
        File src = new File("C:\\Users\\Admin\\Desktop\\a.mp4");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(src));
            byte[] buf = new byte[1024 * 1024];
            int len;
            int count = 1;
            while ((len = bis.read(buf)) != -1) {
                bos = new BufferedOutputStream(new FileOutputStream("d:\\dy\\" + (count++) + ".mp4"));
                bos.write(buf, 0, len);
//                count++;
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void merge() throws Exception {
        ArrayList<FileInputStream> a = new ArrayList<>();
        File file = new File("d:\\dy");
        System.out.println(file.length());
        File[] list = file.listFiles();
        System.out.println(list.length);
        int l = list.length;
        for (int i = 1; i <= l; i++) {
            a.add(new FileInputStream("d:\\dy\\" + i + ".mp4"));
        }
        final Iterator<FileInputStream> it = a.iterator();
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
            @Override
            public boolean hasMoreElements() {
                return it.hasNext();
            }

            @Override
            public FileInputStream nextElement() {
                return it.next();
            }
        };
        SequenceInputStream ss = new SequenceInputStream(en);

        FileOutputStream fs = new FileOutputStream("d:\\dy\\a.mp4");
        byte[] buf = new byte[1024];
        int len;
        while ((len = ss.read(buf)) != -1) {
            fs.write(buf, 0, len);
        }
    }
}
